<template>
  <el-dialog
    custom-class="custom-dialog-ware-edit-style" style="margin-top: -5vh;"
    :visible.sync="modal" title="课件详情" width="80%" @close="customClose">
      <el-form
        :model="ruleForm"
        style="width: 800px"
        :rules="rules"
        ref="ruleForm"
        label-width="70px"
        class="demo-ruleForm"
      >
        <el-form-item label="培训类型" prop="type_ids">
          <el-cascader
            :show-all-levels="false"
            :options="options2"
            style="width: 100%"
            v-model="ruleForm.selected_type_ids"
            :props="{ multiple: true, checkStrictly: true }"
            @change="handleChange"
            clearable
          ></el-cascader>
        </el-form-item>
        <el-form-item label="课件名称" prop="title">
          <el-input v-model="ruleForm.title" maxlength="50" show-word-limit placeholder="请输入"></el-input>
        </el-form-item>
        <el-form-item label="课件时长" prop="duration">
          <div class="flex">
            <el-input-number
              class="input_number"
              v-model="ruleForm.duration"
              :step="1"
              :precision="0"
              :min="0.1"
            ></el-input-number>
            <span style="flex-shrink: 0; margin-left: 10px; font-size: 12px">分钟</span>
          </div>
        </el-form-item>
        <el-form-item label="学时" prop="hour">
          <el-input v-model="ruleForm.hour" placeholder="请输入"></el-input>
        </el-form-item>
        <el-form-item label="关联教师" prop="teacher_id">
          <div class="flex">
            <el-select style="width: 100%" v-model="ruleForm.teacher_id" placeholder="请选择" >
              <el-option :label="item.username" :value="item.id" v-for="(item, index) in teachers" :key="index">{{item.username}}</el-option>
            </el-select>
          </div>
        </el-form-item>
        <el-form-item label="上传课件" prop="video_url">
          <p class="prompt">{{ruleForm.video_url}}</p>
          <template v-if="ruleForm.video_url.endsWith('m3u8')">
            <video-player
              class="video-player vjs-custom-skin"
              ref="videoPlayer"
              :options="playerOptions"
              v-if="ruleForm.video_url"
            />
          </template>
          <template v-else>
            <video :src="ruleForm.video_url" controls style="max-height: 150px;" v-if="ruleForm.video_url"></video>
          </template>
          <el-upload action="#" :show-file-list="false" accept=".mp4" :on-change="uploadvideo">
            <el-button type="primary">上传本地视频</el-button>
          </el-upload>
        </el-form-item>
        <el-form-item label="课件封面" prop="img_url">
          <p class="prompt">建议上传尺寸225*160，格式JPG、PNG、JPEG</p>
          <el-upload
            class="avatar-uploader"
            action="#"
            :show-file-list="false"
            accept=".jpg, .png, jpeg"
            :on-change="(file) => handleAvatarSuccess(file, 1)"
            :before-upload="beforeAvatarUpload"
          >
            <img v-if="ruleForm.img_url" :src="ruleForm.img_url" class="avatar" />
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>
        <el-form-item label="课后习题" prop="exercisesId">
          <el-button type="primary" size="mini" style="flex-shrink: 0; margin-left: 10px" @click="addTest"
          >添加
          </el-button>
        </el-form-item>
      </el-form>
      <el-table
        :data="tableData"
        border
        empty-text="暂无数据"
        no-filtered-userFrom-text="暂无筛选结果"
        style="width: 100%; margin-bottom: 60px"
      >
        <el-table-column fixed type="index" align="center" label="序号" width="50" />
        <el-table-column fixed prop="title" align="center" show-overflow-tooltip label="题目内容" min-width="240" />
        <el-table-column prop="type_name" align="center" label="题目类型" width="140">
          <template slot-scope="scope">
            <p v-if="scope.row.type == 1">单选题</p>
            <p v-else-if="scope.row.type==2">多选题</p>
            <p v-else>判断题</p>
          </template>
        </el-table-column>
        <el-table-column
          prop="options"
          align="center"
          show-overflow-tooltip
          label="题目选项"
          min-width="200"
        ></el-table-column>
        <el-table-column prop="answer" align="center" label="题目答案" width="140"></el-table-column>
        <el-table-column prop="type_name" align="center" label="培训类型" width="140"></el-table-column>
        <el-table-column>
          <template slot-scope="scope">
            <el-button type="text" style="color: red;" @click="delTest(scope.row.id)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <!--<div class="acea-row row-right page" style="margin-bottom: 80px;">-->
      <!--  <el-pagination-->
      <!--    style="margin-top: 5px"-->
      <!--    @size-change="sizeSearch"-->
      <!--    @current-change="search"-->
      <!--    :current-page.sync="queryData.page"-->
      <!--    :page-size.sync="queryData.size"-->
      <!--    layout="total, sizes, prev, pager, next, jumper"-->
      <!--    :total="total"-->
      <!--  >-->
      <!--  </el-pagination>-->
      <!--</div>-->

    <div class="footer">
      <el-button @click="back">关闭</el-button>
      <el-button type="primary" size="medium" @click="submitForm('ruleForm')">确认</el-button>
    </div>

    <addtopic :options="options2" :topic_ids="ruleForm.topic_ids" @set-type-ids="setTypeIds" ref="add"/>

  </el-dialog>

</template>

<script>
import request from '@/libs/request';
import addtopic from './addtopic.vue';
import { Hls } from 'videojs-contrib-hls';

export default {
  name: 'addCourseware',
  components: {
    addtopic,
  },
  data() {
    return {
      modal: false,
      teachers: [],
      interval: '',
      playerOptions: {
        autoplay: false,
        hls: true,
        aspectRatio: '16:9',
        fluid: false,
        sources: [
          {
            src: '',
            type: 'application/x-mpegURL'
          }
        ]
      },
      ruleForm: {
        id: '',
        title: '',
        type_ids: [],
        selected_type_ids: [],
        duration: null,
        teacher_id: '',
        hour: '',
        topic_ids: [],
        video_url: '',
        exercisesId: '',
        img_url: '',
      },
      rules: {
        title: [{ required: true, message: '请输入课件名称', trigger: 'blur' }],
        hour: [{ required: true, message: '请输入学时', trigger: 'blur' }],
        type_ids: [{ required: true, message: '请选择培训类型', trigger: 'change' }],
        duration: [{ required: true, message: '请输入课件时长', trigger: 'blur' }],
        teacher_id: [{ required: true, message: '请选择关联教师', trigger: 'change' }],
        // video_url: [{ required: true, message: '请上传课件', trigger: 'change' }],
      },
      isShowAdd: false,
      addData: {},
      options2: [],
      total: 0,
      isTableLoading: false,
      tableData: [],
      isShowAdd2: false,
      queryData: {
        name: '',
        type: [],
        page: 1,
        size: 5,
      },
    };
  },
  computed: {},
  created() {
  },
  mounted() {
    this.getList1();
  },
  methods: {
    customClose() {
      this.ruleForm.video_url = ''
    },
    setTypeIds (ids) {
      this.ruleForm.topic_ids = ids
      this.getSelectedList()
    },
    getInfo() {
      let loading = this.$loading()
      request({
        url: '/courseware/info',
        method: 'post',
        data: this.ruleForm
      }).then(res => {
        loading.close()
        if (this.ruleForm.id) {
          this.ruleForm = res.data.data
          this.playerOptions.sources[0].src = this.ruleForm.video_url
          this.$refs['ruleForm'].clearValidate()
          this.options2 = res.data.types
          this.teachers = res.data.teachers
          this.getSelectedList()
        } else {
          this.ruleForm = {
            id: '',
            title: '',
            type_ids: [],
            selected_type_ids: [],
            duration: null,
            teacher_id: '',
            hour: '',
            topic_ids: [],
            video_url: '',
            exercisesId: '',
            img_url: '',
          }
          this.playerOptions.sources[0].src = ''
          this.$refs['ruleForm'].clearValidate()
          this.options2 = res.data.types
          this.teachers = res.data.teachers
          this.getSelectedList()
        }
      }).catch(err => {
        // this.$message.error(err.msg)
        loading.close()
      })
    },
    showModal(id=''){
      this.modal = true
      this.ruleForm.id = id
      this.getInfo()
    },
    search(d) {
      if (typeof d == 'number') {
        this.queryData.page = d;
      } else {
        this.queryData.page = 1;
      }
      this.getList1();
    },
    sizeSearch(d) {
      this.queryData.size = d;
      this.search();
    },
    reset() {
      this.queryData.name = '';
      this.queryData.type = '';
      this.queryData.type_ids = [];
      this.search();
    },
    addTest() {
      this.$refs.add.showModal()
    },
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          let loading = this.$loading()
          request({
            url: '/courseware/save',
            method: 'post',
            data: this.ruleForm
          }).then(res => {
            loading.close()
            this.$message.success('操作成功')
            this.modal = false
            this.$parent.getList()
            this.getList1()
          }).catch(err => {
            this.$message.error(err.msg);
            loading.close()
          })
        } else {
          // this.$message.error('请正确填写！');
          return false;
        }
      });
    },
    handleAvatarSuccess(file, type) {
      let loading = this.$loading()
      let formData = new FormData()
      formData.append('file', file.raw)
      request.post('/teacher/upload', formData, {
        file: true
      }).then(res => {
        loading.close()
        this.ruleForm.img_url = res.data.url
      }).catch(err => {
        loading.close()
        this.$message.error(err.msg)
      })
    },
    uploadvideoAction(file) {
      if (this.interval) {
        clearInterval(this.interval)
      }
      this.interval = setTimeout(() => {
        let loading = this.$loading()
        let formData = new FormData()
        formData.append('file', file.raw)
        formData.append('id', this.ruleForm.id)
        request.post('https://shipina.anshangwang.com/merchant/Test/shipin2', formData, {
          file: true,
          noBaseURL: true,
        }).then(res => {
          loading.close()
          this.ruleForm.video_url = res.data
          this.playerOptions.sources[0].src = res.data
        }).catch(err => {
          loading.close()
          this.$message.error(err.msg)
        })
      }, 800)
    },
    uploadvideo(file) {
      // if (file && this.ruleForm.id) {
      if (file) {
        this.uploadvideoAction(file)
      }
    },
    beforeAvatarUpload(file) {
      const isLt2M = file.size / 1024 / 1024 < 5;
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 5MB!');
      }
      return isLt2M;
    },
    getList1() {
      this.isTableLoading = true;
      this.tableData = [];
      this.total = 2;
      this.isTableLoading = false;
    },
    getSelectedList() {
      this.tableData = []
      this.total = 0
      if (this.ruleForm.topic_ids.length > 0) {
        request({
          url: '/courseware/questionlist',
          data: {ids: this.ruleForm.topic_ids},
          method: 'post',
        }).then(res => {
          this.tableData = res.data.list
          this.total = res.data.total
        })
      }
    },
    back() {
      this.modal = false;
    },
    handleChange(value) {
      if (value) {
        this.ruleForm.type_ids = value.map(item => {
          return item[item.length - 1]
        })
      }
    },
    delTest(id) {
      this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        // 删除ruleForm中topic_ids中对应的id
        let index = this.ruleForm.topic_ids.indexOf(id)
        this.ruleForm.topic_ids.splice(index, 1)
        this.getSelectedList()
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    }
  },
};
</script>

<style scoped>
.flex {
  display: flex;
  align-items: center;
}

.avatar-uploader /deep/ .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  width: 150px;
  height: 106px;
  display: flex;
  align-items: center;
}

.avatar-uploader /deep/ .el-upload:hover {
  border-color: #409eff;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 100%;
  line-height: 106px;
  text-align: center;
}

.avatar {
  width: 100%;
  display: block;
}

.prompt {
  font-size: 12px;
  color: #8c939d;
  margin-bottom: 5px;
}

.input_number {
  width: 100%;
  text-align: center;
}

.demo-ruleForm /deep/ .el-input-number__decrease,
.demo-ruleForm /deep/ .el-input-number__increase {
  display: block !important;
}

.footer {
  width: 100%;
  height: 60px;
  position: absolute;
  bottom: 0;
  left: 0;
  z-index: 9;
  background: #ffffff;
  display: flex;
  align-items: center;
  justify-content: center;
  border-top: 1px solid #e6e6e6;
}

.head {
  width: 100%;
  display: flex;
  align-items: center;
  flex-wrap: wrap;
  background: #ffffff;
  border-radius: 5px;
}

.input {
  display: flex;
  align-items: center;
  margin-right: 15px;
  margin-bottom: 20px;
}

.input > span {
  font-size: 12px;
  flex-shrink: 0;
}

.btn {
  margin-bottom: 20px;
}

.video-player {
  max-width: 300px;
}
</style>
<style>
.custom-dialog-ware-edit-style>.el-dialog__body{
  height: 75vh;
}
</style>